const fs = require("fs");

// 封装成一个大对象,每个url下对应一个函数
const router = {
  "/favicon.ico": (res) => {},
  //--------------home-----------
  "/home": (res) => {
    renderHtml(res, "./static/home.html");
  },
  //--------------login-----------------
  "/login": (res) => {
    renderHtml(res, "./static/login.html");
  },
  //--------------404-----------------
  "/404": (res) => {
    renderHtml(res, "./static/error.html");
  },
};

// 导出对象
module.exports = router;

// 渲染页面函数
function renderHtml(res, htmlPath, type = "text/html") {
  preRender(htmlPath)
    .then((data) => {
      res.writeHead(200, { "Content-Type": `${type};charser=utf8 ` });
      res.end(data);
    })
    .catch((err) => {
      console.log(err);
    });
}

// 预渲染
function preRender(path) {
  return new Promise((resolve, reject) => {
    let rs = fs.createReadStream(path, "utf-8");
    let data = "";
    // 监听数据流动
    rs.on("data", (chunk) => {
      data += chunk;
    });
    //  流结束后打印数据
    rs.on("end", () => {
      resolve(data);
    });

    // 发生错误
    rs.on("error", (err) => {
      reject(err);
    });
  });
}
